# 共通文件处理
from fastapi import UploadFile, HTTPException
import os
# 保存图标文件到本地

# 本地存储路径 - 使用与文件相同的存储目录
LOCAL_STORAGE_PATH = "/home/iscxiao/columba/static_resources/chance_uploads"
# STATIC_HOST_URL = "http://localhost:8110/chance_uploads/"
STATIC_HOST_URL = "https://fmh.intasect.com.cn/resources/chance_uploads/"

# 获取在线文件路径，只用于mp时调用
def get_static_file_url(fileNm):
    if not fileNm:
        return ""
    if fileNm.startswith("http"):
        return fileNm
    return STATIC_HOST_URL + fileNm

# 确保存储目录存在
def ensure_directory_exists(path):
    if not os.path.exists(path):
        os.makedirs(path)
# 获取文件扩展名
def get_file_extension(filename):
    if "." in filename:
        return filename.rsplit(".", 1)[1].lower()
    return ""
def save_icon_to_local(file: UploadFile, notice_id: str) -> str:
    # 确保存储目录存在
    ensure_directory_exists(LOCAL_STORAGE_PATH)
    
    # 生成唯一文件名
    file_extension = get_file_extension(file.filename)
    unique_filename = f"{notice_id}.{file_extension}" if file_extension else f"{notice_id}"
    
    # 完整文件路径
    file_path = os.path.join(LOCAL_STORAGE_PATH, unique_filename)
    
    # 保存文件
    try:
        with open(file_path, "wb") as buffer:
            content = file.file.read()
            buffer.write(content)
        return unique_filename
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"图标保存失败: {str(e)}")